#合并购物车，
#登录时读取cookie数据，如果是空跳过购物车，如果非空，解密加入redis，登录后跳转页面
#读取cookie购物车数据，有则合并
#初始化3个容器newcart newselectedids newunselectedids
#遍历字典，遍历时组织新购物车字典添加选中id和未选id
#连接redis 更新hash 更新set数据 合并后删除cookie
import pickle
import base64
from django_redis import get_redis_connection

def merge_cookie_to_redis(request,response):

    cookie_cart=request.COOKIES.get('cart')
    if cookie_cart is not None:
        carts=pickle.loads(base64.b64decode(cookie_cart))
        #3个容器
        new_carts={}
        selected_ids=[]
        unselected_ids=[]
        for sku_id,count_selected_dict in carts.items():
            #新购物车字典
            new_carts[sku_id]=count_selected_dict['count']

            if count_selected_dict['selected']:
                selected_ids.append(sku_id)

            else:
                unselected_ids.append(sku_id)

        redis_cli=get_redis_connection('carts')
        pipeline=redis_cli.pipeline()
        pipeline.hmset('carts_%'%request.user.id,new_carts)
        if len(selected_ids)>0:
            pipeline.sadd('selected_%s'%request.user.id,*selected_ids)#*是拆包

        if len(unselected_ids)>0:
            pipeline.srem('selected_%s'%request.user.id,*unselected_ids)

        pipeline.excute()#管道三部曲，创建，收集，执行

        response.delete_cookie('carts')
    return response




















































